// H5唤醒app
import { isIos } from './enviorment'
const qs = require('qs')

const PROTOCOL = ''
const timeout = 3 * 1000
let timer = null
let callSuccess = false

function isIOS9 () {
  // 获取固件版本
  const getOsv = function () {
    const reg = /OS ((\d+_?){2,3})\s/
    if (navigator?.userAgent?.match(/iPad/i) || navigator?.platform?.match(/iPad/i) || navigator?.userAgent?.match(/iP(hone|od)/i) || navigator?.platform?.match(/iP(hone|od)/i)) {
      const osv = reg.exec(navigator.userAgent)
      if (osv.length > 0) {
        return osv[0].replace('OS', '').replace('os', '').replace(/\s+/g, '').replace(/_/g, '.')
      }
    }
    return ''
  }
  const osv = getOsv()
  const osvArr = osv.split('.')
  // 初始化显示ios9引导
  if (osvArr && osvArr.length > 0) {
    if (parseInt(osvArr[0]) >= 9) {
      return true
    }
  }
  return false
}
// 通过iframe唤醒app
function createIframe (path) {
  const iframe = document.createElement('iframe')
  iframe.setAttribute('id', 'callApp')
  iframe.style.display = 'none'
  iframe.src = path
  document.body.appendChild(iframe)
  setTimeout(() => {
    iframe.parentNode.removeChild(iframe)
  }, 2000)
}
const IOS = isIos()
const IOS9 = isIOS9()

const callApp = (setting) => {
  setting = Object.assign({ path: '', query: {}, protocol: PROTOCOL, success: () => {}, error: () => {}, appStore: '', androidStore: '' }, setting)
  callSuccess = false
  const { path, query, protocol, appStore, androidStore, success, error } = setting
  let property = 'hidden'
  let eventName = 'visibilitychange'
  const queryData = Object.keys(query).length > 0 ? '?' + qs.stringify(query) : ''
  const scheme = protocol + '://' + path + queryData
  if (!IOS9 && IOS) {
    createIframe(scheme)
  } else if (IOS) {
    window.location.href = scheme
  } else {
    createIframe(scheme)
    // window.location.href = scheme
  }
  if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support
    property = 'hidden'
    eventName = 'visibilitychange'
  } else if (typeof document.msHidden !== 'undefined') {
    property = 'msHidden'
    eventName = 'msvisibilitychange'
  } else if (typeof document.webkitHidden !== 'undefined') {
    property = 'webkitHidden'
    eventName = 'webkitvisibilitychange'
  }
  const pageEventChange = function (e) {
    if (document[property] || e.hidden || document.visibilityState === 'hidden') {
      callSuccess = true
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
      // 不同浏览器机制问题，监听可能会无效
      success()
    } else {
      error()
      // todo
    }
    document.removeEventListener(eventName, pageEventChange)
    document.removeEventListener('baiduboxappvisibilitychange', pageEventChange)
  }
  document.addEventListener(eventName, pageEventChange, false)
  document.addEventListener('baiduboxappvisibilitychange', pageEventChange, false)
  timer = setTimeout(() => {
    document.removeEventListener(eventName, pageEventChange)
    document.removeEventListener('baiduboxappvisibilitychange', pageEventChange)
    if (callSuccess) {
      return null
    }
    if (isIos) {
      window.location.href = appStore || 'https://www.baidu.com'
    } else {
      window.location.href = androidStore || 'https://www.baidu.com'
    }
  }, timeout)
}
export default callApp
